<?php

namespace App\Http\Controllers\Purchase;

use App\Http\Controllers\BaseController;
use App\Models\Purchase\PurchaseOrder;
use App\Models\Purchase\PurchaseOrderProcess;
use App\Models\Purchase\PurchasePreSettleOrder;
use App\Models\Purchase\PurchasePreSettleOrderSub;
use App\Models\Steel\SteelArchive;
use App\Models\Stock\Stock;
use App\Services\Common\TableExtFeild;
use App\Services\Purchase\PurchaseCommon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

/**
 * 预结算单
 */
class PurchasePreSettleOrderController extends BaseController
{
    /**
     * 预结算单列表
     */
    public function getorderlist(Request $request)
    {
        $isgetall = $request->isgetall ?? 0;
        $cpid = $this->mangerinfo['cpid'];
        $manger_id = $this->mangerinfo['id'];
        if ($this->mangerinfo['utype'] == 4) {
            $manger_id = 0; //查询所有订单
        }
        $list = PurchasePreSettleOrder::getList($request, $cpid, $manger_id, $isgetall);
        //计算子订单数据到主订单
        $list['list'] = PurchaseCommon::getOrderSum($list['list']);
        return response()->json(['code' => '000', 'msg' => '操作成功', 'data' => $list]);
    }

    /**
     * 批量重新计价--获取
     */
    public function dooncemorechangeprice(Request $request)
    {
        $cpid = $this->mangerinfo['cpid'];
        $manger_id = $this->mangerinfo['id'];
        $order_id = $request->order_id ?? 0;
        $info = PurchasePreSettleOrder::with('suborder')->where(['cpid' => $cpid, 'manger_id' => $manger_id, 'is_del' => 1, 'id' => $order_id, 'settle_status' => 1, 'settle_model' => 3])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '无效参数']);
        }
        //判断是否可以基价---什么依据

        //判断是否完结
        $finishcount = PurchaseOrderProcess::where(['order_id' => $info->order_id,  'cpid' => $cpid, 'is_del' => 1, 'is_finish' => 2])->count();
        if ($finishcount > 0) {
            return response()->json(['code' => '001', 'msg' => '订单已完结，不可重新计价']);
        }

        $info = $info->toArray();
        //获取价格重新计算
        DB::beginTransaction();
        try {
            foreach ($info['suborder'] as $suborder) {
                $stockinfo = Stock::where('id', $suborder['stock_id'])->first()->toArray();
                $steel_archive_info = SteelArchive::where('id', $stockinfo['steel_archive_id'])->first()->toArray();

                //取后结算的时间区间的平均值

                $baseprice = PurchaseCommon::getsettleprice($cpid, $steel_archive_info['steel_factory_id'], $info['settle_model_start_time'], $info['settle_model_end_time']);

                if ($baseprice <= 0) {
                    continue;
                }
                $price = mathfuncmoney('add', $baseprice, $suborder['add_price']);
                $data = [
                    'price' => $price,
                    'total_money' => mathfuncmoney('mul', mathfuncweight('div', $suborder['total_weight'], 1000, 4), $price, 0)
                ];
                PurchasePreSettleOrderSub::where(['id' => $suborder['id'], 'pre_settle_order_id' => $order_id, 'is_del' => 1])->update($data);
            }
            PurchasePreSettleOrder::where(['cpid' => $cpid, 'manger_id' => $manger_id, 'is_del' => 1, 'id' => $order_id, 'settle_status' => 1, 'settle_model' => 3])
                ->update(['update_at' => time()]);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '重新基价失败' . $e->getMessage()]);
        }



        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    /**
     * 完结
     */
    public function dofinish(Request $request)
    {
        $cpid = $this->mangerinfo['cpid'];
        $manger_id = $this->mangerinfo['id'];
        $order_id = $request->order_id ?? 0;
        $info = PurchasePreSettleOrder::where(['cpid' => $cpid, 'manger_id' => $manger_id, 'is_del' => 1, 'id' => $order_id, 'settle_status' => 1, 'settle_model' => 3])->first();
        if (!$info) {
            return response()->json(['code' => '001', 'msg' => '无效参数']);
        }

        //完结逻辑
        PurchasePreSettleOrder::where(['cpid' => $cpid, 'manger_id' => $manger_id, 'is_del' => 1, 'id' => $order_id, 'settle_status' => 1, 'settle_model' => 3])
            ->update(['settle_status' => 2, 'settle_at' => time()]);

        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }

    /**
     * 一键批量
     */
    public function dooncemorechangepriceall(Request $request)
    {
        $order_id_arr = $request->order_id_arr ?? [];
        $cpid = $this->mangerinfo['cpid'];
        $manger_id = $this->mangerinfo['id'];
        $order_id_arr = is_array($order_id_arr) ? $order_id_arr : (is_array(json_decode($order_id_arr, true)) ? json_decode($order_id_arr, true) : []);
        if (count($order_id_arr) <= 0) {
            return response()->json(['code' => '001', 'msg' => '无效参数']);
        }
        $count = PurchasePreSettleOrder::where(['cpid' => $cpid, 'manger_id' => $manger_id, 'is_del' => 1, 'settle_status' => 1, 'settle_model' => 3])->whereIn('id', $order_id_arr)->count();
        if ($count != count($order_id_arr)) {
            return response()->json(['code' => '001', 'msg' => '完结订单不可重新计价']);
        }
        $orderlist = PurchasePreSettleOrder::with('suborder')->where(['manger_id' => $manger_id, 'cpid' => $cpid, 'is_del' => 1, 'settle_status' => 1, 'settle_model' => 3])->whereIn('id', $order_id_arr)->get()->toArray();

        DB::beginTransaction();
        try {
            foreach ($orderlist as $info) {
                //判断是否可以重新基价--什么依据

                //判断是否完结
                $finishcount = PurchaseOrderProcess::where(['order_id' => $info['order_id'],  'cpid' => $cpid, 'is_del' => 1, 'is_finish' => 2])->count();
                if ($finishcount > 0) {
                    DB::rollBack();
                    return response()->json(['code' => '001', 'msg' => '订单已完结，不可重新计价']);
                }

                $order_id = $info['id'];
                foreach ($info['suborder'] as $suborder) {
                    // $stockinfo = Stock::where('id', $suborder['stock_id'])->first()->toArray();
                    // $baseprice=PurchaseCommon::getpriceavg($stockinfo['material_id'], $cpid, $info['create_at'], time());

                    $stockinfo = Stock::where('id', $suborder['stock_id'])->first()->toArray();
                    $steel_archive_info = SteelArchive::where('id', $stockinfo['steel_archive_id'])->first()->toArray();
                    $baseprice = PurchaseCommon::getsettleprice($cpid, $steel_archive_info['steel_factory_id'], $info['settle_model_start_time'], $info['settle_model_end_time']);

                    if ($baseprice <= 0) {
                        continue;
                    }
                    $price = mathfuncmoney('add', $baseprice, $suborder['add_price']);
                    $data = [
                        'price' => $price,
                        'total_money' => mathfuncmoney('mul', mathfuncweight('div', $suborder['total_weight'], 1000, 4), $price, 0)
                    ];
                    PurchasePreSettleOrderSub::where(['id' => $suborder['id'], 'pre_settle_order_id' => $order_id, 'is_del' => 1])->update($data);
                }
                PurchasePreSettleOrder::where(['cpid' => $cpid, 'manger_id' => $manger_id, 'is_del' => 1, 'id' => $order_id, 'settle_status' => 1, 'settle_model' => 3])
                    ->update(['update_at' => time()]);
            }
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json(['code' => '001', 'msg' => '重新基价失败' . $e->getMessage()]);
        }
        //获取价格重新计算

        return response()->json(['code' => '000', 'msg' => '操作成功']);
    }
}
